import { useTokenStore } from '@/stores/token.js'
//定制请求实例
//创建请求实例
import axios from "axios";
const baseURL = "/api"
const instance = axios.create({ baseURL });
import { ElMessage } from "element-plus";
import router from '@/router'

//添加请求拦截
instance.interceptors.request.use(
  config => {
    //添加token
    const tokenStore = useTokenStore()
    //如果tokenStore.token不为空，则Authorization添加token
    console.log(tokenStore.token);
    if (tokenStore.token) {
      config.headers.token = tokenStore.token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
)

//添加响应拦截
instance.interceptors.response.use(
  result => {
    if (result.data.code === 0) {
      return result.data;
    }
    if (result.data.description === "验证码错误") {
      ElMessage({
        showClose: true,
        message: result.data.description ? result.data.description : "服务异常",
        type: 'error',
      })
      return result.data;
    }
    ElMessage({
      showClose: true,
      message: result.data.description ? result.data.description : "服务异常",
      type: 'error',
    })
    //alert(result.data.msg ? result.data.msg : "服务异常")
    return Promise.reject(result.data);
  },
  err => {
    //判断状态码若401，则跳转登录页
    if (err.response.status === 401) {
      ElMessage({
        showClose: true,
        message: "请先登录",
        type: 'error',
      })
      router.push('/login')
    } else {
      ElMessage({
        showClose: true,
        message: "服务异常",
        type: 'error',
      })
    }
    return Promise.reject(err);
  }
)
export default instance;